package cn.hunqing.web.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hunqing.web.entity.JsSDKConfig;
import cn.hunqing.web.util.WeChatUtils;
import cn.hunqing.web.util.JsSDKSign;

@Controller
public class WXJsSDKController {
	private static Logger logger = LoggerFactory.getLogger(WXJsSDKController.class);
	private static final String APP_ID = "wx341e6568d7ecbb95";

	@RequestMapping(value = "/wx/getJsSDKConfig")
	@ResponseBody
	public JsSDKConfig getJsSDKConfig(HttpServletRequest request, String targetUrl) {
		// String url = CommonsUtils.getHttpWebappName();
		if (StringUtils.isBlank(targetUrl)) {
			throw new RuntimeException("jsapiTicket获取失败,当前url为空！！");
		}
		int index = targetUrl.indexOf("#");
		if (index > 0) {
			targetUrl = targetUrl.substring(0, index);
			logger.debug("targetUrl：" + targetUrl);
		}

		String accessToken = WeChatUtils.getToken();

		String jsTickt = WeChatUtils.getjsTicket(accessToken);

		logger.info("accessToken is :" + accessToken);
		logger.info("jsTickt is :" + jsTickt);
		logger.info("Step3, get the openif by the appid:" + WeChatUtils.APP_ID);
		Map<String, String> ret = JsSDKSign.sign(jsTickt, targetUrl);
		logger.info("the jsSDK sign info is :" + ret.toString());
		logger.info("the jsSDK sign nonceStr  is :" + ret.get("nonceStr"));
		logger.info("the jsSDK sign timestamp is :" + ret.get("timestamp"));
		logger.info("the jsSDK sign timestamp is :" + ret.get("signature"));
		JsSDKConfig jsSDKConfig = new JsSDKConfig();
		jsSDKConfig.setAppId(APP_ID);
		jsSDKConfig.setNonceStr(ret.get("nonceStr"));
		jsSDKConfig.setTimestamp(ret.get("timestamp"));
		jsSDKConfig.setSignature(ret.get("signature"));
		logger.debug(jsSDKConfig.toString());
		return jsSDKConfig;

	}
}
